package test;

import org.bytedeco.javacv.FFmpegFrameGrabber;
import org.bytedeco.javacv.FFmpegFrameRecorder;
import org.bytedeco.javacv.Frame;

import static java.lang.Thread.sleep;

public class SaveVideo {
    static int num = 2; //录制视频数量
    final static long time = 5; //每个视频的时间
    final static int rate = 10000000;
    final static int fps = 25;
    final static int width = 1920;
    final static int height = 1080;
    static int i = 0;
    public static void main(String[] args)
            throws Exception {
        String inputFile = "rtsp://admin:123456789a@192.168.31.66:554/h264/ch1/main/av_stream";
        while(true){
                new Thread(() -> {
                    String outputFile = "D:\\FFTB\\"+(i++)+".mp4";
                    try {
                        frameRecord(inputFile,outputFile, time);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }).start();
            num--;
            if (num==0)
                break;
            sleep(time*1000);
        }
    }
    public static void  frameRecord(String inputFile, String outputFile,Long m) throws Exception{
        boolean isStart = true;
        FFmpegFrameGrabber grabber = new FFmpegFrameGrabber(inputFile);
        grabber.setOption("rtsp_transport","tcp");
        grabber.setFrameRate(fps);
        grabber.setVideoBitrate(rate);
        FFmpegFrameRecorder recorder = new FFmpegFrameRecorder(outputFile, width, height,1);
        recorder.setFrameRate(fps);
        recorder.setVideoBitrate(rate);
        recordByFrame(grabber, recorder, isStart,m);
    }

    private static void recordByFrame(FFmpegFrameGrabber grabber, FFmpegFrameRecorder recorder, Boolean status,Long m)
            throws Exception{
        try {
            grabber.start();
            recorder.setVideoCodec(grabber.getVideoCodec());
            recorder.start();
            Frame frame = null;
            //计算帧数
            long index=m*fps*2;
            //已经录制帧数
            long finishIndex=0L;
            //Long start=CommonUtil.getSecondTimestamp();
            while (status&& (frame = grabber.grabFrame()) != null) {
                recorder.record(frame);
                finishIndex++;
                //Long end=CommonUtil.getSecondTimestamp();
                if(index<=finishIndex){
                    System.out.println("完成录制");
                    break;
                }
            }
            recorder.stop();
            grabber.stop();
        } finally {
            if (grabber != null) {
                grabber.stop();
            }
        }
    }


}